import { defineStore } from 'pinia';
import { clearToken, setToken, setTokenHeader } from '@/utils/auth';
import { getUserInfo, login, LoginParam, logout } from '@/api/auth-api';
import { useRouterStore } from '@/store';
import { removeRouteListener } from '@/utils/route-listener';
import type { UserState } from '@/store/modules/user/types';
import {sysUserInfo} from "@/api/api-sys.ts";

const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      id: 0,
      username: '',
      nickname: '',
      phone: '',
      email: '',
      avatar: '',
      roles: [],
      permission: [],
      super:null,
      is_oath:null
    };
  },
  getters: {
    getRoles(): string[] {
      return this.roles;
    },
    getPermissions(): string[] {
      return this.permission;
    },
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },
  actions: {
    async logout() {
      try {
        // 调用退出接口
        await logout({action:'logout'});
      } finally {
        await this.clearInfo();
      }
    },

    async clearInfo() {
      this.resetInfo();
      clearToken();
      // 重置菜单
      const routerStore = useRouterStore();
      routerStore.resetInfo();
      removeRouteListener();
    },

    setInfo(partialState: Partial<UserState>) {
      this.$patch(partialState);
    },

    resetInfo() {
      this.$reset();
    },

    async loadInfo() {
      let params = {
        avatar: "",
        create_time: "2024-08-30 17:48:00",
        email: "",
        id: 2,
        last_login_ip: "183.156.212.134",
        last_login_time: "2024-12-23 14:19:42",
        layout: "",
        login_count: 37,
        nickname: "test01",
        phone: "",
        type: 1,
        update_time: "",
        username: "test01",
      }
      const { body } = await sysUserInfo({action:'info'});
      let data = {
        avatar:body.head,
        create_time: body.create_time,
        // email: "",
        id: body.id,
        // last_login_ip: "183.156.212.134",
        // last_login_time: "2024-12-23 14:19:42",
        // layout: "",
        // login_count: 37,
        nickname: body.name,
        phone: body.account,
        type: body.type,
        // update_time: "",
        username:body.name,
        is_oath:body.is_oath,
        super:body.super
      }
      this.setInfo(data);
    },

    setPermissions(permission: string[]) {
      this.permission = permission;
    },
  },
});

export default useUserStore;
